﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Security.Principal;
using System.Diagnostics;
using System.IO;

namespace AppUpgrader
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            LogUtils.WriteLog("AppUpgrader 已启动...");
            Process otherInstance = GetRunningInstance();
            if (otherInstance != null)
            {
                LogUtils.WriteLog("发现已经存在的更新进程，id=" + otherInstance.Id);
                LogUtils.WriteLog("准备关闭已经存在的更新进程......");
                //关闭之前的进程
                otherInstance.Kill();
                otherInstance = null ;
            }
            if (Environment.CurrentDirectory.StartsWith(@"C:\Program Files"))
                Elevate();
        }

        #region 权限提升
        public void Elevate()
        {
            // 如果不是以administrator身份运行
            if (!IsRunAsAdmin())
            {
                // 以administrator身份，重启自己
                ProcessStartInfo proc = new ProcessStartInfo();
                proc.UseShellExecute = true;
                proc.WorkingDirectory = Environment.CurrentDirectory;
                proc.FileName = Path.Combine(Environment.CurrentDirectory, "AppUpgrader.exe");
                proc.Verb = "runas";
                try
                {
                    Process.Start(proc);
                }
                catch
                {
                    // 如果用户拒绝提升权限，直接退出
                }
                Environment.Exit(-1);   // 退出
            }
        }
        #endregion

        /// <summary>
        /// 检查当前进程是否以administrator身份运行
        /// </summary>
        /// <returns>
        /// </returns>
        private bool IsRunAsAdmin()
        {
            WindowsIdentity id = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(id);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private Process GetRunningInstance()
        {
            System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess();
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process process in processes) //查找相同名称的进程
            {
                if (process.ProcessName == current.ProcessName && process.Id != current.Id)  //忽略当前进程
                { //确认相同进程的程序运行位置是否一样. 
                    if (System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", @"\") == current.MainModule.FileName)
                    { //Return the other process instance.                       
                        return process;
                    }
                }
            } //No other instance was found, return null. 
            return null;
        }  
    }
}
